//
//  CHLoginViewController.m
//  SZTZ
//
//  Created by 陈浩 on 2017/3/6.
//  Copyright © 2017年 陈浩. All rights reserved.
//

#import "CHLoginViewController.h"
#import "CHTabBarController.h"
#import "CHProgressHUD.h"
#import "PublicClass.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "CHTableViewCell.h"
#import "AFNetWorkService.h"
#import "CHPopView.h"
#import "CHSectionModel.h"
#import "MBProgressHUD+PKX.h"
#import "CHUUIDManager.h"
@interface CHLoginViewController ()<CHPopViewDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    CGSize keyboardSize;
    CGRect popViewFrm;
    BOOL isSection;
    BOOL isExpand;   //  展开
    NSString *cdnpath;
}

@property (weak, nonatomic) IBOutlet UIImageView *headImgView;

@property (weak, nonatomic) IBOutlet UILabel *institutionLabel;
@property (weak, nonatomic) IBOutlet UITextField *sectionField;      //  部门
@property (weak, nonatomic) IBOutlet UITextField *usernameTextField;      //  用户名
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;    //  手机号码
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;         //  验证码
@property (weak, nonatomic) IBOutlet UIImageView *pullImgView;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;     //  验证码btn
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (nonatomic ,strong) NSMutableArray *datas;
@property (nonatomic ,strong) NSMutableArray *datas1;
@property (nonatomic ,strong) NSMutableArray *resultArr;
@property (nonatomic ,strong) CHPopView *popView;
@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,assign) NSInteger secondsCountDown;
@property (nonatomic ,strong) NSTimer *countDownTimer;

@property (nonatomic ,copy) NSString *firstKey;
@property (nonatomic ,copy) NSString *secondKey;
@property (nonatomic ,strong) UIButton *noticeBtn;
@property (nonatomic ,strong) UIAlertView *myAlertView;

- (IBAction)textFieldDidChange:(UITextField *) TextField;
- (IBAction)loginBtnClick:(id)sender;
- (IBAction)sendCode:(id)sender;

@end

@implementation CHLoginViewController

-(NSMutableArray *)resultArr{
    if (!_resultArr) {
        _resultArr = [NSMutableArray array];
    }
    return _resultArr;
}


-(NSMutableArray *)datas{
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}


-(NSMutableArray *)datas1{
    if (!_datas1) {
        _datas1 = [NSMutableArray array];
    }
    return _datas1;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _firstKey = nil;
    _secondKey = nil;
    isSection = NO;
    

    self.sectionField.delegate = self;
    self.codeTextField.delegate = self;
    self.phoneNumberTextField.delegate = self;
    self.usernameTextField.delegate = self;
    self.sectionField.userInteractionEnabled = YES;
    self.pullImgView.userInteractionEnabled= NO;
    UIButton *btn = [[UIButton alloc] initWithFrame:self.sectionField.bounds];
    btn.userInteractionEnabled = YES;
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.sectionField addSubview:btn];
    self.noticeBtn = btn;
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    [self.institutionLabel addGestureRecognizer:tap];

    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    [self.pullImgView addGestureRecognizer:tap1];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
//    
//    NSString *leapName = LeapAPPName;
//    [self checkVersion:leapName];
    
}

-(void)btnClick{
    
    [CHProgressHUD showError:@"请先选择机构"];
    
    
}

-(void)keyboardWillShow:(NSNotification *)note{

    NSDictionary *info = [note userInfo];
    
    NSValue *value = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    keyboardSize = [value CGRectValue].size;
//    NSLog(@"%@",NSStringFromCGSize(keyboardSize));
    
}


- (void)keyboardWillHide:(NSNotification *)note
{
   
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.view.frame = CGRectMake(0, 0, UIScreenW, UIScreenH);
             self.tableView.frame = CGRectMake(self.sectionField.frame.origin.x, self.sectionField.frame.origin.y + self.sectionField.frame.size.height + 3 , self.sectionField.frame.size.width, 200);
            self.popView.transform = CGAffineTransformIdentity;
        }];
    
    
    
}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [MBProgressHUD showMessage:@"正在加载数据"];
    [self loadData];
    
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.tableView  = [[UITableView alloc] initWithFrame:CGRectMake(self.sectionField.frame.origin.x, self.sectionField.frame.origin.y + self.sectionField.frame.size.height + 3, self.sectionField.frame.size.width, 200) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1];;
    self.tableView.hidden = YES;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    [window addSubview:self.tableView];
}




-(void)loadData{
    
    [[Globle getInstance].service RequestWithServiceName:@"fgwoa_getDwForAPP1" params:nil httpMethod:@"GET" resultIsDictionary:true completeBlock:^(id result) {
        if([Util getNetState] == 0){
            [CHProgressHUD showError:@"无网络连接"];
        }
        if (result) {
            [MBProgressHUD hideHUD];
            NSMutableArray *tempArr = [NSMutableArray array];
            for (NSMutableDictionary *dict in result) {
                
                NSLog(@"%@",dict);
                CHSectionModel *model = [CHSectionModel objectWithKeyValues:dict];
                
                [tempArr addObject:model];
            }
            
            self.datas = tempArr;
        }
    }];
}


#pragma mark -   登录
- (IBAction)loginBtnClick:(id)sender {
    
    BOOL isChinese = [PublicClass isValidChinese:self.usernameTextField.text];
    BOOL isMatchNumber = [PublicClass valiMobile:self.phoneNumberTextField.text];
    if ([Util getNetState] == 0) {
        [CHProgressHUD showError:@"无网络连接"];
    }else{
        if ([self.institutionLabel.text isEqualToString:@"请选择机构"]) {
            
            [CHProgressHUD showError:@"请选择机构"];
        } else if (self.sectionField.text.length == 0 && ![self.sectionField.placeholder isEqualToString:@"无下级部门"]){
            
            if ([self.institutionLabel.text isEqualToString:@"其他"]) {
                [CHProgressHUD showError:@"请填写部门"];
            }else{
                [CHProgressHUD showError:@"请填写部门或下拉选择"];
            }
        }else if (self.usernameTextField.text.length == 0|| isChinese == false) {
            [CHProgressHUD showError:@"请输入正确姓名"];
        }else if(self.phoneNumberTextField.text.length == 0 || isMatchNumber == false){
            
            [CHProgressHUD showError:@"请输入正确手机号"];
            
        }else if (self.codeTextField.text.length == 0){
            
            [CHProgressHUD showError:@"请输入短信验证码"];
            
        }else{
            if ([Util getNetState] == 0 ) {
                [MBProgressHUD showError:@"无网络连接"];
            }else{
                [self login];
            }
            
            
        }
        
    }
    
    
}

-(void)login{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"shebeihao"] =  [[UIDevice currentDevice].identifierForVendor UUIDString];
    params[@"mobilephone"] = self.phoneNumberTextField.text;
    params[@"username"] = self.usernameTextField.text;
    params[@"code"] = self.codeTextField.text;
    [[Globle getInstance].service requestWithServiceName:@"fgwoa_loginValidate" params:params httpMethod:@"POST" resultIsDictionary:false completeBlock:^(id result) {
        
        NSLog(@"登录结果%@",result);
        
        
        if ([result isEqualToString:@"true"]) {
            //  存储到偏好，记录是否已登录
            [Util setBool:YES key:@"isLogin"];
            
            NSUUID*UUID=[UIDevice currentDevice].identifierForVendor;
            [CHUUIDManager deleteUUID];
            [CHUUIDManager saveUUID:UUID.UUIDString];
            [CHUUIDManager saveUserName:self.usernameTextField.text];
            [Util setObject:self.usernameTextField.text key:@"username"];
            [Util setObject:self.phoneNumberTextField.text key:@"phonenumber"];
            [Globle getInstance].userName= self.usernameTextField.text;
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            CHTabBarController *tabBarVC = [[CHTabBarController alloc] init];
            window.rootViewController = tabBarVC;
            
        }else{
            
            [CHProgressHUD showError:@"登录失败"];
        }
    }];
    
    
    
}


- (IBAction)sendCode:(id)sender {
    [self.view endEditing:YES];
    
    BOOL isChinese = [PublicClass isValidChinese:self.usernameTextField.text];
    BOOL isMatchNumber = [PublicClass valiMobile:self.phoneNumberTextField.text];
    
    if ([Util getNetState] == 0) {
        
        [CHProgressHUD showError:@"无网络连接"];
    }else{
        
        if ([self.institutionLabel.text isEqualToString:@"请选择机构"]) {
            
            [CHProgressHUD showError:@"请选择机构"];
            
        } else if (self.sectionField.text.length == 0 && ![self.sectionField.placeholder isEqualToString:@"无下级部门"]){
            
            if ([self.institutionLabel.text isEqualToString:@"其他"]) {
               [CHProgressHUD showError:@"请填写部门"];
            }else{
               [CHProgressHUD showError:@"请填写部门或下拉选择"];
            }
            
        }else if (self.usernameTextField.text.length == 0|| isChinese == false) {
            
            [CHProgressHUD showError:@"请输入真实姓名"];
            
            
        }else if(self.phoneNumberTextField.text.length == 0 || isMatchNumber == false   ){
            
            [CHProgressHUD showError:@"请输入正确手机号"];
            
        }else{
            
            //开始计时
            [self startCountDownTimer];
            // 发送验证码
            [self sendCodeMessage];
            
        }
        
        
    }
}


#pragma mark - 发送验证码
-(void)sendCodeMessage{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"mobilephone"] = self.phoneNumberTextField.text;
    params[@"userName"] = self.usernameTextField.text;
    params[@"jg"] = _firstKey;
    params[@"bm"] = _secondKey;
    NSLog(@"%@",params);
    [[Globle getInstance].service requestWithServiceName:@"fgwoa_send_Verification_Code" params:params httpMethod:@"POST" resultIsDictionary:true completeBlock:^(id result) {
        
        NSLog(@"发送验证码%@",result);
        
        if (result != nil) {
            
            if ([result[@"restate"] isEqualToString:@"2"]) {
                //  登录过一次以上的用户
                [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
                
            }else if([result[@"restate"] isEqualToString:@"1"]){
                // 第一次登录的用户
                
            }else{
                
                [CHProgressHUD showError:@"验证码发送失败"];
            }
        }
    }];
}


-(void)startCountDownTimer{
    
    _secondsCountDown = 60;
    [_codeBtn setTitle:[NSString stringWithFormat:@"%zds后重发",_secondsCountDown] forState:UIControlStateNormal];
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
    _codeBtn.enabled = NO;
}




-(void)timeFireMethod{
    
    _secondsCountDown--;
    
    [_codeBtn setTitle:[NSString stringWithFormat:@"%zds后重发",_secondsCountDown] forState:UIControlStateNormal];
    
    if (_secondsCountDown<0) {
        
        [_countDownTimer invalidate];
        
        _codeBtn.enabled=YES;
        
        [_codeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        
    }
    
}


-(void)tapGesture:(UITapGestureRecognizer *)tap{
    
    if (tap.view == self.institutionLabel) {
        
        
        [self.sectionField resignFirstResponder];
        [self.usernameTextField resignFirstResponder];
        [self.phoneNumberTextField resignFirstResponder];
        [self.codeTextField resignFirstResponder];
        
        
        
        CHPopView *popView = [[CHPopView alloc] initWithFrame:CGRectMake(tap.view.frame.origin.x, CGRectGetMaxY(tap.view.frame), tap.view.frame.size.width, 150)];
        popView.isSection = YES;
        popView.delegate = self;
        popView.layer.cornerRadius = 5;
        popView.layer.masksToBounds = YES;
        popView.bgColor = [UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1];
        popView.datas = self.datas;
        [popView presentPopViewToView:tap.view];
        self.popView = popView;
        popViewFrm = popView.frame;
    }else{
        isExpand = YES;
        self.tableView.hidden = NO;
        [self.tableView reloadData];
    }
}




#pragma mark  - CHPopViewDelegate
-(void)popViewDidSelectRowAtIndex:(NSInteger)index{
    [self.datas1 removeAllObjects];
    [MBProgressHUD showMessage:@"正在加载数据"];
    self.sectionField.text = nil;
    self.sectionField.userInteractionEnabled = YES;
    [self.sectionField resignFirstResponder];
    CHSectionModel *model = self.datas[index];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"key"] = model.codeid;
    
    [[Globle getInstance].service RequestWithServiceName:@"fgwoa_getSecondary_units" params:params httpMethod:@"POST" resultIsDictionary:TRUE completeBlock:^(id result) {
       
        
        NSLog(@"二级菜单%@",result);
        if (result) {
            
            [MBProgressHUD hideHUD];
            NSLog(@"%@",[result[@"data"] class]);
            
            if (result[@"data"] == [NSNull null]) {
                
                if ([model.codevalue isEqualToString:@"其他"]) {
                    [self.sectionField setPlaceholder:@"请填写部门"];
                    self.tableView.hidden = YES;
                    
                }else{
                    
                    self.sectionField.userInteractionEnabled = NO;
                    [self.sectionField setPlaceholder:@"无下级部门"];
                }
                self.pullImgView.userInteractionEnabled = NO;
                self.pullImgView.hidden = YES;
                
                
            }else{
                self.pullImgView.userInteractionEnabled = YES;
                [self.sectionField setPlaceholder:@"请填写部门或下拉选择"];
                self.pullImgView.hidden = NO;
                for (NSMutableDictionary *dict in result[@"data"]) {
                    
                    CHSectionModel *model = [CHSectionModel objectWithKeyValues:dict];
                    [self.datas1 addObject:model];
                }
            }
        }
    }];

    
    _firstKey = model.codeid;
    [self.institutionLabel setText:model.codevalue];
    [self.institutionLabel setTextColor:[UIColor blackColor]];
    if (![self.institutionLabel.text isEqualToString:@"请选择机构"]) {
        if (self.noticeBtn) {
            [self.noticeBtn removeFromSuperview];
        }
    }
}





-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSLog(@"网络连接%d",[Util getNetState]);
    if([Util getNetState] == 0){
        [MBProgressHUD showError:@"无网络连接"];
    }
}





- (IBAction)textFieldDidChange:(UITextField *) TextField{
    
    [self textFileSearch:TextField.text];
    
}


- (void)textFieldDidBeginEditing:(UITextField *)textField{
    isExpand = NO;
    NSLog(@"%@",NSStringFromCGSize(keyboardSize));

    
    
    UIToolbar *bar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0, UIScreenW,44)];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(UIScreenW - 60, 7,50, 30)];
    [button setTitle:@"完成"forState:UIControlStateNormal];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [bar addSubview:button];
    textField.inputAccessoryView = bar;
    
    CGFloat offsetY = textField.frame.origin.y +44 - (UIScreenH - 326 -35);
    if (offsetY >0) {
        
        
        if (textField == self.sectionField) {
            [UIView animateWithDuration:0.3 animations:^{
                
                self.view.frame = CGRectMake(0, -offsetY - 100, UIScreenW, UIScreenH);
                self.tableView.frame = CGRectMake(self.sectionField.frame.origin.x, self.sectionField.frame.origin.y + self.sectionField.frame.size.height + 3 -offsetY - 100, self.sectionField.frame.size.width, 200);
                self.popView.frame = CGRectMake(popViewFrm.origin.x, popViewFrm.origin.y-offsetY - 100, popViewFrm.size.width, popViewFrm.size.height);
            }];
           
        }else{
            
            [UIView animateWithDuration:0.3 animations:^{
                self.view.frame = CGRectMake(0, -offsetY , UIScreenW, UIScreenH);
                self.tableView.frame = CGRectMake(self.sectionField.frame.origin.x, self.sectionField.frame.origin.y + self.sectionField.frame.size.height + 3 -offsetY , self.sectionField.frame.size.width, 200);
                self.popView.frame = CGRectMake(popViewFrm.origin.x, popViewFrm.origin.y -offsetY, popViewFrm.size.width, popViewFrm.size.height);
            }];
          
        }
       
    }
    
    
    
    
    
}

-(void)textFileSearch:(NSString *)TextField{
    if ([self.institutionLabel.text isEqualToString:@"其他"]) {
        self.tableView.hidden = YES;
    }else{
        
        if (TextField == nil || [TextField isEqualToString:@""] ) {
            
            [self.tableView reloadData];
            
        }else{
            
            self.tableView.hidden = NO;
            //    // 完成具体的搜索功能
            //    // 1.清空搜索结果数组
            [self.resultArr removeAllObjects];
            
            int k = 0;
            
            //2。通过循环数据，找出与搜索关键字匹配的内容，把匹配的内容添加到数组中
            
            for (CHSectionModel *model in self.datas1) {
                
                NSString *ste = [NSString stringWithFormat:@"%@",model.codevalue];
                
                
                NSRange range = [ste rangeOfString:TextField];
                
                if (range.length) {
                    
                    [self.resultArr addObject:ste];
                    
                }
                
                k++;
                
                [self.tableView reloadData];
                
            }
        }

    }
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.sectionField.text == nil || self.sectionField.text.length == 0 || isExpand == YES) {
        
        return self.datas1.count;
    }
    
    return self.resultArr.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"textcell"];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"textcell"];
        
    }
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.backgroundColor =  [UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1];
    
    if (self.sectionField.text == nil || self.sectionField.text.length == 0 || isExpand == YES) {
        CHSectionModel *model = self.datas1[indexPath.row];
        cell.textLabel.text = model.codevalue;
    }else{
        cell.textLabel.text = self.resultArr[indexPath.row];
    }
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (self.sectionField.text == nil || self.sectionField.text.length == 0 || isExpand == YES) {
        CHSectionModel *model = self.datas1[indexPath.row];
        _secondKey = model.codeid;
        self.sectionField.text = model.codevalue;
    }else{
        self.sectionField.text = self.resultArr[indexPath.row];
    }
    self.tableView.hidden = YES;
    isExpand = NO;
    
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}





////当用户全部清空的时候的时候 会调用
//-(BOOL)textFieldShouldClear:(UITextField *)textField{
//
//    self.tableView.hidden = NO;
//
//    [self.tableView reloadData];
//
//    return YES;
//
//}
//
////可以得到用户输入的字符
//-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//
//    return YES;
//
//}

////已经开始编辑的时候 会触发这个方法
//- (void)textFieldDidBeginEditing:(UITextField *)textField{
//
//    if (self.text != nil) {
//
//        [self textFileSearch:self.text];
//
//    }
//
//    self.tableView.hidden = NO;
//
//}
//
////结束编辑的时候调用
//
//-(void)textFieldDidEndEditing:(UITextField *)textField{
//
//    self.text = textField.text;
//
//    self.tableView.hidden = YES;
//
//    self.resultTableView.hidden = YES;
//
//
//}
//
////点击Return键的时候，（标志着编辑已经结束了）

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    return YES;
    
}

#pragma mark - UITextFieldDelegate
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    self.tableView.hidden = YES;
    [self.sectionField resignFirstResponder];
    [self.usernameTextField resignFirstResponder];
    [self.phoneNumberTextField resignFirstResponder];
    [self.codeTextField resignFirstResponder];
    
}


-(void)buttonClick{
    
  
    [self.sectionField resignFirstResponder];
    [self.usernameTextField resignFirstResponder];
    [self.phoneNumberTextField resignFirstResponder];
    [self.codeTextField resignFirstResponder];
    
}


//
//补全分割线
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell  respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])
    {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


#pragma mark 检测版本号
-(void)checkVersion:(NSString *)leapAPPname
{
    if(leapAPPname != nil)
    {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        [params setValue:leapAPPname forKey:@"appname"];
        
        
        [[Globle getInstance].service RequestWithServiceName:@"lbcp_getAppVersion" params:params httpMethod:@"POST" resultIsDictionary:TRUE completeBlock:^(id result) {
            
            NSLog(@"result:%@",result);
            
            NSDictionary *dic = (NSDictionary *)result;
            if(nil != dic)
            {
                [MBProgressHUD hideHUD];
                //获取本地版本
                NSString *localVersion = VersionCode;
                NSLog(@"当前版本号%@",localVersion);
                int localVersionNUm = (localVersion == nil ? -1 : [localVersion intValue]);
                //获取服务器版本
                NSString *serverVersion = [dic valueForKey:@"appversion"];
                NSLog(@"服务器版本%@",serverVersion);
                cdnpath = [dic valueForKey:@"cdnpath"];
                int serverVersionNum = (serverVersion == nil ? -1 : [serverVersion intValue]);
                //判断是非升级
                if(localVersionNUm < serverVersionNum)
                {
                    NSString *upgrade = [dic valueForKey:@"upgrade"];
                    if([@"1" isEqualToString:upgrade])    //   强制升级
                    {
                        
                        self.myAlertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"有新的版本，请及时更新。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                    }
                    else
                    {
                        self.myAlertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"有新的版本，请及时更新。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",@"取消", nil];
                    }
                    
                    //                    [self.myAlertView show];
                    
                    if(nil != cdnpath && ![@"" isEqualToString:cdnpath])
                    {
                        [self.myAlertView show];
                    }
                    
                }
            }
            
        }];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(alertView == self.myAlertView)
    {
        if(buttonIndex == 0)
        {
            NSString *urlStr = [NSString stringWithFormat:@"itms-services://?action=download-manifest&url=%@",cdnpath];
            NSLog(@"全路径%@",urlStr);
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
        }
    }
    
}



@end
